/*
 * Copyright (C) 2010, Funcom AS, All Rights Reserved
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  @authors
 *  Svein Gunnar Larsen <sveingunnarlarsen@gmail.com>
 *  Erik Thune Lund <culex.eriklund@gmail.com>
 *  Michel Krohn-Dale <kronicz@gmail.com>
 */

package com.funcom.peeler.utils;

import com.funcom.peeler.UpdateCont;
import com.funcom.peeler.WorkBench;
import com.funcom.peeler.symbol.Symbol;
import com.jmex.bui.Rule;
import com.jmex.bui.property.BackgroundProperty;

import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

public class WorkBenchMenuBar extends JMenuBar {

    private WorkBench workbench;

    /**
     * Constructs a menubar for the workbench
     * @param workbench Reference to parent workbench
     */
    public WorkBenchMenuBar( final WorkBench workbench ) {
        super();

        this.workbench = workbench;

        JMenu fileMenu = new JMenu( "File" );

        JMenuItem menuItem = new JMenuItem( "Open" );
        menuItem.setToolTipText( "CTRL + O" );
        menuItem.addActionListener( new ActionListener() {

            public void actionPerformed( ActionEvent e ) {
                UpdateCont.get().loadNewWorkBench();
            }
        });
        fileMenu.add( menuItem );

        menuItem = new JMenuItem( "Save" );
        menuItem.setToolTipText( "CTRL + S" );
        menuItem.addActionListener( new ActionListener() {

            public void actionPerformed( ActionEvent e ) {
                workbench.saveWorkSpace();
            }
        });
        fileMenu.add( menuItem );

        menuItem = new JMenuItem( "Export Canvas" );
        menuItem.setToolTipText( "CTRL + E" );
        menuItem.addActionListener( new ActionListener() {

            public void actionPerformed( ActionEvent e ) {
                workbench.exportCanvas();
            }
        });
        fileMenu.add( menuItem );

        menuItem = new JMenuItem( "Close" );
        menuItem.setToolTipText( "CTRL + Q" );
        menuItem.addActionListener( new ActionListener() {

            public void actionPerformed( ActionEvent e ) {
                workbench.close();
            }
        });
        fileMenu.add( menuItem );

        add( fileMenu );

        JMenu editMenu = new JMenu( "Edit" );

        menuItem = new JMenuItem( "Settings" );
        editMenu.add( menuItem );
        menuItem.addActionListener( new ActionListener() {

            public void actionPerformed( ActionEvent e ) {
                workbench.getBui().getPeelRoot().getSettings().setVisible( true );
            }
        });

        JMenu resourceList = new JMenu( "Resources" );

        JMenu stylesheetList = new JMenu( "Stylesheets" );
        stylesheetList.addMenuListener( getStyleSheetListener( stylesheetList ) );
        resourceList.add( stylesheetList );

        JMenu bundleList = new JMenu( "Resource Bundle");
        bundleList.addMenuListener( getResourceBundleListener( bundleList ) );
        resourceList.add( bundleList );

        JMenu imageList = new JMenu( "Images" );
        imageList.addMenuListener( getImagesListener( imageList ) );
        resourceList.add( imageList );

        JMenuItem exportItem = new JMenuItem( "Export List" );
        exportItem.addActionListener( getExportListener() );
        resourceList.add( exportItem );

        add( editMenu );
        add( resourceList );
    }

    /**
     *
     * @param menu Menu to add listener
     * @return new MenuAdapter
     */
    private MenuListener getStyleSheetListener( final JMenu menu ) {

        return new MenuAdapter() {

            public void menuSelected( MenuEvent e ) {
                menu.add( workbench.getBui().getPeelRoot().getStyleSheetPath() );
            }

            public void menuDeselected( MenuEvent e ) {
                menu.removeAll();
            }
        };
    }

    /**
     *
     * @param menu Menu to add listener
     * @return new MenuAdapter
     */
    private MenuListener getImagesListener( final JMenu menu ) {

        return new MenuAdapter() {

            public void menuSelected( MenuEvent e ) {

                for ( Rule rule : workbench.getWorkBenchStyle().properties.values() ) {

                    if ( rule.properties.containsKey( Symbol.StyleProperty.background ) ) {

                        BackgroundProperty value = (BackgroundProperty)rule.properties.get( Symbol.StyleProperty.background );

                        if ( value.ipath != null ) menu.add( value.ipath );
                    }

                }
            }

            public void menuDeselected( MenuEvent e ) {
                menu.removeAll();
            }
        };
    }

    /**
     *
     * @param menu Menu to add listener
     * @return new MenuAdapter
     */
    private MenuListener getResourceBundleListener( final JMenu menu ) {

        return new MenuAdapter() {

            public void menuSelected( MenuEvent e ) {
                if ( !workbench.getBui().getPeelRoot().getSettings().getLocalizerPath().equals("") )
                    menu.add( workbench.getBui().getPeelRoot().getSettings().getLocalizerPath() );
            }

            public void menuDeselected( MenuEvent e ) {
                menu.removeAll();
            }
        };
    }

    /**
     *
     * @return new ActionListener
     */
    private ActionListener getExportListener() {

        return new ActionListener() {

            public void actionPerformed( ActionEvent e ) {

                JFileChooser chooser = new JFileChooser( workbench.getBui().getPeelRoot().getLastPath() );
                chooser.setFileSelectionMode( chooser.FILES_ONLY );
                int opt = chooser.showDialog( WorkBenchMenuBar.this, "Export Resource List");

                if ( opt == chooser.APPROVE_OPTION ) {
                    exportResources( chooser.getSelectedFile().getPath() );
                }
            }
        };
    }

    /**
     * Exports a list of the existing resources to a txt file
     * @param filename 
     */
    private void exportResources( String filename ) {

        try {
            FileWriter out = new FileWriter( filename );

            out.write( "Resource List\n\n" );

            out.write( "-Stylesheet: " + workbench.getBui().getPeelRoot().getStyleSheetPath() + "\n\n" );

            out.write( "-Resource Bundle: " + workbench.getBui().getPeelRoot().getSettings().getLocalizerPath() + "\n\n" );

            out.write( "-Images\n\n" );
            for ( Rule rule : workbench.getWorkBenchStyle().properties.values() ) {

                if ( rule.properties.containsKey( Symbol.StyleProperty.background ) ) {

                BackgroundProperty value = (BackgroundProperty)rule.properties.get( Symbol.StyleProperty.background );

                if ( value.ipath != null ) out.write( value.ipath + "\n" );
                }
            }
            out.close();
        }
        catch ( FileNotFoundException e ) {
            JOptionPane.showMessageDialog( WorkBenchMenuBar.this, "File " + filename + " not found!" );
        }
        catch ( IOException e ) {
            e.printStackTrace();
        }
    }
}
